package org.xiaojinlong.algo;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author Jin Long
 * 2015/8/19
 */
public class ResizingArrayStack<Item> implements Stack<Item> {
    private Item[] a; // 存放栈元素
    private int N; // 栈里元素的总数

    public ResizingArrayStack() {
        a = (Item[]) new Object[2];
    }

    @Override
    public boolean isEmpty() {
        return N == 0;
    }

    @Override
    public int size() {
        return N;
    }

    private void resize(int capacity) {
        assert capacity >= N;
        Item[] temp = (Item[]) new Object[capacity];
        for (int i = 0; i < N; i++) {
            temp[i] = a[i];
        }
        a = temp;
    }

    @Override
    public void push(Item item) {
        if (N == a.length) {
            resize(2 * a.length);
        }
        a[N++] = item;
    }

    @Override
    public Item pop() {
        if (isEmpty()) {
            throw new NoSuchElementException("Stack underflow");
        }

        Item item = a[N-1];
        a[N-1] = null; // to avoid loitering
        N--;
        if (N > 0 && N == a.length / 4) {
            resize(a.length / 2);
        }

        return item;
    }

    @Override
    public Item peek() {
        if (isEmpty()) {
            throw new NoSuchElementException("Stack underflow");
        }

        return a[N - 1];
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        for (Item item : this) {
            s.append(item).append(" ");
        }

        return s.toString();
    }

    @Override
    public Iterator<Item> iterator() {
        return new ReverseArrayIterator();
    }

    private class ReverseArrayIterator implements Iterator<Item> {
        private int i;

        ReverseArrayIterator() {
            i = N - 1;
        }

        @Override
        public boolean hasNext() {
            return i >= 0;
        }

        @Override
        public Item next() {
            // 手动操作Iterator时可以随意调用next() 因此需要保证不会出错
            if (!hasNext()) {
                throw new NoSuchElementException();
            }

            return a[i--];
        }
    }
}

